package com.tensquare.user.service;

import java.util.*;
import java.util.concurrent.TimeUnit;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.persistence.criteria.Selection;
import javax.transaction.Transactional;

import org.apache.commons.lang.RandomStringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import org.springframework.web.bind.annotation.RequestMapping;
import util.IdWorker;

import com.tensquare.user.dao.UserDao;
import com.tensquare.user.pojo.User;

/**
 * 服务层
 * 
 * @author Administrator
 *
 */
@Service
public class UserService {

	@Autowired
	private UserDao userDao;
	
	@Autowired
	private IdWorker idWorker;
	@Autowired
	private RabbitTemplate rabbitTemplate;

	@Autowired
    private RedisTemplate redisTemplate;
	@Autowired
	BCryptPasswordEncoder encoder;
	public List<User> findAll() {

		return userDao.findAll();
	}

	/**
	 * 分页查询
	 * 
	 * @param page
	 * @param size
	 * @return
	 */
	public Page<User> findPage(int page, int size) {
		PageRequest pageRequest = new PageRequest(page-1, size);
		return userDao.findAll(pageRequest);
	}

	private Specification<User> where(Map searchMap) {
		
		return new Specification<User>() {
          
			@Override
			public Predicate toPredicate(Root<User> root,CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> predicateList = new ArrayList<Predicate>();
                // ID
                if (searchMap.get("id")!=null && !"".equals(searchMap.get("id"))) {
                	predicateList.add(cb.like(root.get("id").as(String.class), "%"+(String)searchMap.get("id")+"%"));
                }
                // 手机号码
                if (searchMap.get("mobile")!=null && !"".equals(searchMap.get("mobile"))) {
                	predicateList.add(cb.like(root.get("mobile").as(String.class), "%"+(String)searchMap.get("mobile")+"%"));
                }
                // 密码
                if (searchMap.get("password")!=null && !"".equals(searchMap.get("password"))) {
                	predicateList.add(cb.like(root.get("password").as(String.class), "%"+(String)searchMap.get("password")+"%"));
                }
                // 昵称
                if (searchMap.get("nickname")!=null && !"".equals(searchMap.get("nickname"))) {
                	predicateList.add(cb.like(root.get("nickname").as(String.class), "%"+(String)searchMap.get("nickname")+"%"));
                }
                // 性别
                if (searchMap.get("sex")!=null && !"".equals(searchMap.get("sex"))) {
                	predicateList.add(cb.like(root.get("sex").as(String.class), "%"+(String)searchMap.get("sex")+"%"));
                }
                // 头像
                if (searchMap.get("avatar")!=null && !"".equals(searchMap.get("avatar"))) {
                	predicateList.add(cb.like(root.get("avatar").as(String.class), "%"+(String)searchMap.get("avatar")+"%"));
                }
                // E-Mail
                if (searchMap.get("email")!=null && !"".equals(searchMap.get("email"))) {
                	predicateList.add(cb.like(root.get("email").as(String.class), "%"+(String)searchMap.get("email")+"%"));
                }
                // 兴趣
                if (searchMap.get("interest")!=null && !"".equals(searchMap.get("interest"))) {
                	predicateList.add(cb.like(root.get("interest").as(String.class), "%"+(String)searchMap.get("interest")+"%"));
                }
                // 个性
                if (searchMap.get("personality")!=null && !"".equals(searchMap.get("personality"))) {
                	predicateList.add(cb.like(root.get("personality").as(String.class), "%"+(String)searchMap.get("personality")+"%"));
                }

                return cb.and( predicateList.toArray(new Predicate[predicateList.size()]));
                
            }
        };		
		
	}

	public Page<User> findSearch(Map whereMap, int page, int size) {
		Specification<User> specification = where(whereMap);
		PageRequest pageRequest = new PageRequest(page-1, size);
		return userDao.findAll(specification, pageRequest);
	}

	public User findOne(String id) {
		User user = userDao.findById(id).get();
		if (user!=null)
		{
			return user;
		}
		return null;
	}

	public void add(User user,String code) {
        String syscode = (String)redisTemplate.opsForValue().get("smscode_" + user.getMobile());
        if (syscode==null)
        {
            throw new RuntimeException("输入验证码不正确");
        }

        user.setId(idWorker.nextId()+""); //主键值
        user.setFollowcount(0);//关注数
        user.setFanscount(0);//粉丝数
        user.setOnline(0L);//在线时长
        user.setRegdate(new Date());//注册日期
        user.setUpdatedate(new Date());//更新日期
        user.setLastdate(new Date());//最后登陆日期
		//密码加密
		String newpassword = encoder.encode(user.getPassword());//加密后的密码
		user.setPassword(newpassword);
		userDao.save(user);
	}
	
	public void update(User user) {
		userDao.save(user);
	}

	public void delete(String id) {
		userDao.deleteById(id);
	}

	public void deleteList(String[] ids) {
		for (String id : ids) {
			userDao.deleteById(id);
		}
	}
	public void sendSms(String mobile){
		String checkcode = RandomStringUtils.randomNumeric(6);
		//向缓存中放一份
		redisTemplate.opsForValue().set("checkcode_"+mobile, checkcode, 5, TimeUnit.MINUTES);
		//给用户发一份
		Map<String, String> map = new HashMap<>();
		map.put("mobile", mobile);
		map.put("checkcode", checkcode);
		//将数据放入mq
		rabbitTemplate.convertAndSend("sms", map);
		//在控制台显示一份【方便测试】
		System.out.println("验证码为："+checkcode);

	}
	/**
	 * 根据手机号和密码查询用户
	 * @param mobile
	 * @param password
	 * @return
	 */
	public User findByMobileAndPassword(String mobile,String password){
		System.out.println(mobile);
		User user = userDao.findByMobile(mobile);
		System.out.println(user);
		if(user!=null && encoder.matches(password,user.getPassword())){
			return user;
		}else{
			return null;
		}
	}
	@Transactional
	public void incFanscount(String userid,int x){
		userDao.incFanscount(userid,x);
	}
	/**
	 * 更新关注数
	 * @param x
	 */
	@Transactional
	public void incFollowcount(String userid,int x){
		userDao.incFollowcount(userid,x);
	}
}
